<?php

/**
 * 验证码分析：宽度，高度，背景，验证码数量，字体大小，字体颜色
 */
class Code {
    private $img;
    private $width;
    private $height;
    private $bgcolor;
    private $codeLen;
    private $fontsize;
    private $fontcolor;
    private $fontfile;

//   构造函数（必须要执行）
    public function __construct($width = null, $heigth = null, $bgcolor = null, $codeLen = null, $fontsize = null, $fontcolor = null) {
        $this->width = intval($width) ? $width : 80;
        $this->height = intval($heigth) ? $heigth : 30;
        $this->bgcolor = $bgcolor ? $bgcolor : "#ffffff";
        $this->codeLen = $codeLen ? $codeLen : 4;
        $this->fontsize = $fontsize ? $fontsize : 18;
        $this->fontcolor = $fontcolor ? $fontcolor : "#000000";
        $this->fontfile = "./simhei.ttf";
    }
    
    /**
     * 显示验证码的函数
     */ 
    public function show() {
        header("Content-type:image/png");
        $this->createbg();//调用创建画布函数
        $this->createttf();//调用写入文字函数
        imagepng($this->img);
    }
    
    /**
     * 创建画布函数
     */
    private function createbg(){
        $img=  imagecreatetruecolor($this->width,  $this->height);//创建一个图像画布        
        $bgcolor=  imagecolorallocate($img, hexdec(substr($this->bgcolor,1,2)), hexdec(substr($this->bgcolor,3,2)), hexdec(substr($this->bgcolor,5,2)));//定义背景颜色
        imagefill($img, 0, 0, $bgcolor);//填充颜色
        imagerectangle($img, 0, 0, $this->width-1,  $this->height-1, imagecolorallocate($img,20, 220, 20));//给图像加上边框
        $this->img=$img;//赋值   
    }
    /**
     * 写入文字函数
     */
    private function createttf(){
       $codeStr="abcdefghijklmnpqrstuvwxyz123456789";//验证码种子
       $code='';
       for($i=0; $i <$this->codeLen;$i++){
           $code.=$codeStr[mt_rand(0, strlen($codeStr))-1];//随机取验证码种子的字符，再连等于$code;
       }
       $code=  strtoupper($code);//转换大写
       $w=  ($this->width-10)/$this->codeLen;//计算每一个验证码所占的空间
       $this->color=  imagecolorallocate($this->img, hexdec(substr($this->fontcolor,1,2)),  hexdec(substr($this->fontcolor,3,2)),  hexdec(substr($this->fontcolor,5,2)));//定义字体颜色
       for($i=0;$i<$this->codeLen;$i++){
           imagettftext($this->img, $this->fontsize, mt_rand(-10, 20), $i*$w+10, mt_rand(20, 26), $this->color, $this->fontfile,$code[$i]);//给图像写入文字
       }       
    }

}

?>
